import pygame

from SnowBros.Entity.Entity import Entity
from SnowBros.Entity.MapDataEntity import MapDataEntity


class FinalSnowBallEntity(Entity):
    def __init__(self, image, pos_x, pos_y):
        # 1. 调用父类方法实现精灵的创建(image/rect/speed)

        super().__init__(
            image, pos_x, pos_y,
            40, 34, False)
        """运动方向，True为正，False为负"""
        self.MoveDir = False
        # 是否应该移动
        self.ShouldMove = False
        # 是否应该下落
        self.ShouldDown = True


    def update(self):
        # 1. 调用父类的方法实现
        self.CurrentTime = pygame.time.get_ticks()
        super().update()
        self.CheckHeight()
        if self.ShouldMove:
            if self.MoveDir:
                self.rect.x += 3
            else:
                self.rect.x -= 3
        if self.ShouldDown:
            self.rect.y += 2

    def Move(self, dir):
        if dir > 0:
            self.MoveDir = True
        else:
            self.MoveDir = False
        self.ShouldMove = True
        self.TargetAttackTime = pygame.time.get_ticks() + 500


    def CheckHeight(self):
        for i in MapDataEntity.MapData:
            """如果与地形离得很近，就判定是不是落在地形上，如果是就停止下落"""
            if 1 >= i - self.rect.y >= 0:
                """记录此高度所有x轴信息"""
                currentKeyValueLength = MapDataEntity.MapData[i].__len__()
                """存于tempGroundGroup中，键为组，每两个数据为一组，比如{1:[1,2],2:[1,2]}"""
                tempGroundGroup = {}
                tempGroundGroupFlag = 0
                temp = []
                for j in range(0, currentKeyValueLength):
                    temp.append(MapDataEntity.MapData[i][j])
                    if temp.__len__() % 2 == 0:
                        tempGroundGroup[tempGroundGroupFlag] = temp[tempGroundGroupFlag * 2:tempGroundGroupFlag * 2 + 2]
                        tempGroundGroupFlag += 1

                for k in tempGroundGroup:
                    if tempGroundGroup[k][1] >= self.rect.x >= tempGroundGroup[k][0]:
                        self.ShouldDown = False
                        return
                self.ShouldDown = True
                return
        self.ShouldDown = True

    def TryKillSelf(self):
        self.kill()
